package oss

import (
	"bytes"
	"fmt"
	"mime/multipart"
	settings "sems/setting"
	"strings"
	"sync"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

var bucketName string
var Client *oss.Client

type FileWithHeader struct {
	Filename   string
	FileHeader *multipart.FileHeader
}

type MultiPicUpload struct {
	Files []*FileWithHeader
}

// UploadMultiplePics  用于并发上传多张图片
func UploadMultiplePics(mpu *MultiPicUpload) ([]string, error) {
	var urls []string
	var wg sync.WaitGroup
	var mu sync.Mutex // 用于同步访问 urls 切片

	for _, fwH := range mpu.Files {
		wg.Add(1)
		go func(fh *FileWithHeader) {
			defer wg.Done()

			// 确保文件名和文件头信息被正确传递
			url, err := UploadPic(fh.Filename, fh.FileHeader)
			if err != nil {
				fmt.Printf("Upload failed for %s: %v\n", fh.Filename, err)
				return
			}

			mu.Lock()
			urls = append(urls, url)
			mu.Unlock()
		}(fwH)
	}

	wg.Wait() // 等待所有图片上传完成
	return urls, nil
}

func UploadPic(filename string, s1 *multipart.FileHeader) (string, error) {

	// 获取存储空间
	bucket, err := Client.Bucket(settings.Conf.OssConfig.BucketName)

	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}

	// 构建年月日文件夹路径
	today := time.Now().Format("20060102") // 格式化为年月日
	objectKey := today + "/" + filename

	// 检查文件夹是否存在，不存在则创建
	isExist, err := bucket.IsObjectExist(today + "/")
	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}
	if !isExist {
		err := bucket.PutObject(today+"/", strings.NewReader(""))
		if err != nil {
			fmt.Println("Error:", err)
			return "", err
		}
	}

	imgInfor, err := s1.Open()
	if err != nil {
		fmt.Println(err.Error())
		return "", err
	}

	// 上传图片
	err = bucket.PutObject(objectKey, imgInfor)
	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}

	// 生成永久有效的访问链接
	signedURL, err := bucket.SignURL(objectKey, oss.HTTPGet, 31536000000)
	if err != nil {
		fmt.Println(err.Error())
	}

	return signedURL, nil
}

func NewUploadPic(filename string, s1 []byte) (string, error) {

	// 获取存储空间
	bucket, err := Client.Bucket(bucketName)
	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}

	// 构建年月日文件夹路径
	today := time.Now().Format("20060102") // 格式化为年月日
	objectKey := today + "/" + filename

	// 检查文件夹是否存在，不存在则创建
	isExist, err := bucket.IsObjectExist(today + "/")
	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}
	if !isExist {
		err := bucket.PutObject(today+"/", strings.NewReader(""))
		if err != nil {
			fmt.Println("Error:", err)
			return "", err
		}
	}

	// 上传图片
	err = bucket.PutObject(objectKey, bytes.NewReader(s1))
	if err != nil {
		fmt.Println("Error:", err)
		return "", err
	}

	// 生成永久有效的访问链接
	signedURL, err := bucket.SignURL(objectKey, oss.HTTPGet, 31536000000)
	if err != nil {
		fmt.Println(err.Error())
	}

	return signedURL, nil
}

func Init(cfg *settings.OssConfig) error {
	var err error
	// 创建 OSS 客户端
	Client, err = oss.New(cfg.Endpoint, cfg.AccessKeyID, cfg.AccessKeySecret)
	if err != nil {
		return err
	}
	bucketName = cfg.BucketName
	return nil
}
